<template>
  <div class="app-container">
    <!--条件搜索表单-->
    <el-row>
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="searchObj.username" placeholder="操作用户" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchObj.operationModule" placeholder="操作模块" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchObj.operationStatus" placeholder="操作状态" clearable @change="getAll()">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchObj.operationType" placeholder="操作类型" filterable clearable @change="getAll()">
            <el-option v-for="item in operationTypes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchObj.operationTimes"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="操作开始时间"
            end-placeholder="操作结束时间"
          />
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getAll()">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reset()">清空</el-button>
      </el-form>
    </el-row>

    <el-row style="margin-top: 10px">
      <el-button v-if="hasPerm('sys:operation-log:batch-delete')" type="danger" icon="el-icon-delete" :disabled="ids.length < 1" @click="batchDelete">
        批量删除
      </el-button>
      <el-button v-if="hasPerm('sys:operation-log:export')" type="primary" icon="el-icon-download" @click="openExport">批量导出</el-button>
    </el-row>

    <!-- 列表 -->
    <el-table
      v-loading="loading"
      element-loading-text="正在努力加载数据中..."
      :data="page.records"
      :border="false"
      stripe
      style="width: 100%; margin-top: 15px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" fixed="left" width="55" />
      <el-table-column type="index" fixed="left" width="80" label="序号" />
      <el-table-column prop="operationUsername" fixed="left" label="操作用户" min-width="120" sortable show-overflow-tooltip />
      <el-table-column prop="operationModule" label="操作模块" min-width="120" show-overflow-tooltip />
      <el-table-column prop="operationType" label="操作类型" show-overflow-tooltip />
      <el-table-column prop="operationIp" label="操作IP" min-width="100" sortable show-overflow-tooltip />
      <el-table-column prop="operationAddr" label="操作地址" show-overflow-tooltip />
      <el-table-column prop="operationStatus" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.operationStatus === '失败'" type="danger">失败</el-tag>
          <el-tag v-if="scope.row.operationStatus === '成功'" type="success">成功</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="operationTime" label="操作时间" min-width="120" sortable show-overflow-tooltip />
      <el-table-column prop="requestTime" label="执行时间" min-width="120" sortable show-overflow-tooltip />
      <!-- 操作 -->
      <el-table-column label="操作" width="100" fixed="right" align="center">
        <template slot-scope="scope">
          <el-link type="primary" icon="el-icon-view" @click="openDetail(scope.row)">详情</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页导航栏 -->
    <div>
      <el-pagination
        :background="true"
        :current-page="pIndex"
        :page-size="pSize"
        :total="page.total"
        :page-sizes="[1, 3, 6, 9, 12, 15, 18]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        @current-change="getAll"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 详情 -->
    <el-dialog title="操作日志详情" :visible.sync="visible" @close="visible = false">
      <el-form :model="operationLog" label-width="80px">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="操作模块">
              {{ operationLog.operationModule }}
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="请求地址">
              <el-button type="text"> {{ operationLog.operationUrl }} </el-button>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="操作人">
              {{ operationLog.operationUsername }}
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="18" :lg="12" :xl="8">
            <el-form-item label="操作地址"> {{ operationLog.operationIp }} / {{ operationLog.operationAddr }} </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="请求方式">
              <el-tag type="info" effect="dark"> {{ operationLog.requestMethod }} </el-tag>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="操作方法">
              {{ operationLog.operationMethod }}
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="请求参数">
              <code>
                {{ operationLog.operationParams }}
              </code>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="返回参数">
              <code>
                {{ operationLog.operationResult }}
              </code>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="操作状态">
              <el-tag v-if="operationLog.operationStatus === '失败'" type="danger">失败</el-tag>
              <el-tag v-if="operationLog.operationStatus === '成功'" type="success">成功</el-tag>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="执行时间"> {{ operationLog.requestTime }} </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="操作时间">
              {{ operationLog.operationTime }}
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item v-if="operationLog.operationStatus == '失败'" label="错误信息">
              {{ operationLog.errorMsg }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导出 -->
    <el-dialog v-if="hasPerm('sys:operation-log:export')" title="导出文件" :visible.sync="exportVisible" @close="exportVisible = false">
      <el-form ref="exportForm" :model="exportObject">
        <el-form-item label="导出条数开始位置" prop="startCount" required>
          <el-input v-model="exportObject.startCount" placeholder="请输入导出条数开始位置" />
        </el-form-item>
        <el-form-item label="导出条数结束位置" prop="endCount" required>
          <el-input v-model="exportObject.endCount" placeholder="请输入导出条数结束位置" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exportVisible = false">取 消</el-button>
        <el-button type="primary" @click="exportData('exportForm')"> 确认 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入api接口定义的js文件
import operationLogApi from '@/api/sys/operation-log'
import dictItemApi from '@/api/sys/dict-item'

export default {
  data() {
    // 定义变量和初始值
    return {
      // 查询相关
      statusOptions: [
        { value: 1, label: '失败' },
        { value: 0, label: '成功' }
      ],
      searchObj: {},

      // 列表相关
      loading: false,
      pIndex: 1, // 当前页
      pSize: 6, // 每页显示记录数
      page: [], // 列表
      ids: [],
      visible: false, // 详情对话框控制
      operationLog: {},
      operationTypes: [], // 操作类型

      // 导出
      exportVisible: false,
      exportObject: {
        startCount: 1,
        endCount: 100
      }
    }
  },
  created() {
    this.getAll()
    this.getDictItem()
  },
  methods: {
    // 获取操作类型
    getDictItem() {
      dictItemApi.getListByDictCode('OPERATION_TYPE').then((res) => {
        this.operationTypes = res.data
      })
    },
    // 加载列表数据
    getAll(current = 1) {
      this.loading = true
      this.pIndex = current
      operationLogApi
        .getPage(this.pIndex, this.pSize, this.searchObj)
        .then((response) => {
          this.page = response.data
          this.loading = false
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 改变页码
    handleSizeChange(pageSize) {
      this.pSize = pageSize
      // 重新调用数据加载方法 --> 方法中已经加入的查询参数
      this.getAll()
    },

    // 复选框选中
    handleSelectionChange(r) {
      // 得到选中的id
      this.ids = r.map((v) => v.id)
    },

    // 批量删除
    batchDelete() {
      if (this.ids.length > 0) {
        this.$confirm('此操作将永久删除登录信息,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          // 确定执行then方法
          .then(() => {
            operationLogApi.batchDelete(this.ids).then((resp) => {
              this.$message.success('删除成功!')
              this.getAll()
            })
          })
      } else {
        this.$message.warning('至少选择一条数据!')
      }
    },

    // 打开导出表单
    openExport() {
      this.exportVisible = true
      this.exportObject = {
        startCount: 1,
        endCount: 100
      }
    },

    // 导出
    exportData(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          operationLogApi
            .exportData(this.exportObject.startCount, this.exportObject.endCount)
            .then((res) => {
              // 如果响应结果为空直接返回
              if (!res) {
                return
              }

              // 得到响应头中的文件名,创建一个临时的 Blob URL
              const fileName = decodeURI(res.headers['content-disposition'].split('=')[1])
              const blob = new Blob([res.data], {
                type: 'application/vnd.vnd.ms-excel;charset=utf-8'
              })
              const url = window.URL.createObjectURL(blob)

              // 创建一个 <a> 元素来容纳下载链接,并设置href 属性设置为 Blob URL
              const link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', fileName)

              // 将链接元素添加到文档的 body 中
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link)

              // 撤销 Blob URL 以释放内存
              window.URL.revokeObjectURL(url)

              // 消息提示
              this.$message.success('导出成功')

              // 隐藏导出弹窗
              this.exportVisible = false
            })
            .catch((err) => {
              console.log('🚀 ~ operationLogApi.exportData ~ err:', err)
            })
        }
      })
    },

    // 打开详情
    openDetail(r) {
      this.visible = true
      this.operationLog = r
    },

    // 重置
    reset() {
      this.searchObj = {}
      this.getAll()
    }
  }
}
</script>

<style></style>
